﻿using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;


//udpThread = new UDPRecvThread();
            //udpThread.ProcssUDPMsg = ProcessUDPMsg;
            //udpThread.Start(4567);

namespace UIFramework
{
    public class UDPRecvThread
    {
        private int port;
        private Thread _recvThread;
        private bool running;
        private int recvBufferSize = 1024;

        Socket sock;

        public delegate void ProcessUDPMsgDelegation(string msg);
        public ProcessUDPMsgDelegation ProcssUDPMsg;

        public bool Running
        {
            get { return running; }
        }

        public int RecvBufferSize
        {
            get { return recvBufferSize; }
            set { recvBufferSize = value; }
        }


        public UDPRecvThread()
        {
        }

        public void Start(int iPort)
        {
            port = iPort;
            _recvThread = new Thread(new ThreadStart(_threadfunc));
            running = true;
            _recvThread.Start();

        }

        public void Stop()
        {
 
            running = false;
            if(sock!=null)
            sock.Close();
        }

        private void _threadfunc()
        {
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, port);
            sock = new Socket(endPoint.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
            sock.Bind(endPoint);
    

            while (running)
            {
                
                if (sock.Available != 0)
                {
                    byte[] recvBuffer = new byte[RecvBufferSize];//buffersize
                    sock.Receive(recvBuffer);
                    string strRecv = Encoding.UTF8.GetString(recvBuffer);
                    strRecv = strRecv.Substring(0, strRecv.IndexOf('\0'));
                    if (ProcssUDPMsg != null)
                    {
                        ProcssUDPMsg(strRecv);
                    }
                }
                else
                {
                    Thread.Sleep(1);
                }
            }
        }
    }
}
